﻿using AutoMapper;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using MS.BasicData.Infrastructure;
using MS.BasicData.Infrastructure.IBasePository;
using MS.BasicData.Read.API.Applications.Command;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace MS.BasicData.Read.API.Applications.CommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, ApiResult>
    {
        private readonly IUserRepository _userRepository;

        private readonly IMapper _mapper;


        private readonly IConfiguration _configuration;

        public LoginCommandHandler(IUserRepository userRepository, IMapper mapper, IConfiguration configuration)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            _configuration = configuration;
        }

        public async Task<ApiResult> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var list = await _userRepository.GetAll(a => a.UserNick == request.UserNick);
            if (list == null)
            {
                return ApiResult.Fail("用户不存在");
            }
            if (list.IsSuc)
            {
                return ApiResult.Fail("账号已被禁用");
            }

            var Token = GenerateToken(list.UserName);
            if(list.Password != request.Password)
            {
                list.ErrNum++;
                if (list.ErrNum < 3)
                {
                    await _userRepository.UpdateAsync(list);
                    return ApiResult.Success($"密码错误，请重试，还剩{3 - list.ErrNum}次机会");
                }
                else
                {
                    list.IsSuc = true;
                    await _userRepository.UpdateAsync(list);
                    return ApiResult.Success($"密码错误，账号已禁用");
                }
            }
            return ApiResult.Success("登录成功", new
            {
               Token, list
            });
        }

        public string GenerateToken(string username)
        {
            var claims = new[]
            {
            new Claim(JwtRegisteredClaimNames.Sub, username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            return new JwtSecurityTokenHandler().WriteToken(token);

        }
    }


    

}
